package com.lagou.util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class IpRateCountUtil {

    //ip请求时间统计map
    private static Map<String, List<Long>> ipRequestTimeMap = new ConcurrentHashMap<>();


    public static boolean checkIpRateThreshold(String ip, Integer x, Integer y) {
        List<Long> requestTimeList = ipRequestTimeMap.get(ip);
        if (requestTimeList == null) {
            requestTimeList = new ArrayList<>();
        }

        Calendar now = Calendar.getInstance();
        long currentTime = now.getTimeInMillis();

        requestTimeList.add(currentTime);


        //获取最近x分钟的时间值
        now.add(Calendar.MINUTE, -x);
        long countStartTime = now.getTimeInMillis();

        //过滤x分钟内的数据
        List<Long> filterRequestTimeList = requestTimeList.stream().filter(time -> time >= countStartTime).collect(Collectors.toList());

        //将过滤后的数据放回map
        ipRequestTimeMap.put(ip, filterRequestTimeList);

        //判断请求频率是否超过配置的阈值
        if (filterRequestTimeList.size() >= y) {
            return true;
        }

        return false;
    }

}
